package com.yiren.manager.ctrl.messhall;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrMeal;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrMealCardRechargeRecord;
import com.yiren.entity.YrMealsCostRecord;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrUserRfidCard;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.ctrl.elder.YrElderBaseController;
import com.yiren.manager.form.base.CommParamForm;
import com.yiren.manager.form.cost.YrMealCardRechargeRecordForm;
import com.yiren.manager.form.department.YrStaffInfoForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.messhall.YrMealCardForm;
import com.yiren.manager.service.iface.base.YrUserRfidCardService;
import com.yiren.manager.service.iface.cost.YrMealCardRechargeRecordService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.service.iface.messhall.YrMealService;
import com.yiren.manager.task.DateUtil;
import com.yiren.manager.utils.ObjectUtils;

@Controller
@RequestMapping("mealCard")
public class YrMealCardController extends YrElderBaseController<YrMealCardForm, YrMealCard>{
	
	@Autowired
	private YrMealCardService selfService;
	
	@Autowired
	private YrUserRfidCardService userRfidCardService;
	
	@Autowired
	private YrElderWalletService elderWalletService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrMealService mealService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrMealCardRechargeRecordService mealCardRechargeRecordService;
	
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrMealCardForm> find(String searchVal) throws Exception{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		String sqlWhere = "card_card_id=?1 OR card_person_name=?2";
		QueryResult<YrMealCard> qr = selfService.find(YrMealCard.class, sqlWhere, new Object[]{searchVal,searchVal});
		if(qr.getTotalRecord()==0){
			throwExp("查询不到相关的饭卡信息");
		}
		List<YrMealCardForm> formList = new ArrayList<YrMealCardForm>();
		for(YrMealCard mealCard : qr.getResultList()){
			YrMealCardForm form = toForm(mealCard);
			
			sqlWhere = "user_relation_id=?1";
			QueryResult<YrUserRfidCard> qrUserRfidCard = userRfidCardService.find(YrUserRfidCard.class, sqlWhere, new Object[]{form.getCardPersonId()});
			
			form.setUserRfidCardForms(qrUserRfidCard.getResultList());
			formList.add(form);
		}
		result.setData(formList);
		
		return result;
	}
	
	@RequestMapping("findByRfidCard")
	@ResponseBody
	public HTTPResult<YrMealCardForm> findByRfidCard(String cardNumber) throws Exception{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		
		String sqlWhere = "card_number=?1 AND status=0";
		QueryResult<YrUserRfidCard> qrUserRfidCard = userRfidCardService.find(YrUserRfidCard.class, sqlWhere, new Object[]{cardNumber});
		if(qrUserRfidCard.getTotalRecord()==0){
			throwExp("查询不到rfid卡或该卡已注销");
		}
		
		 sqlWhere = "card_card_id=?1";
		
		QueryResult<YrMealCard> qr = selfService.find(YrMealCard.class, sqlWhere, new Object[]{qrUserRfidCard.getResultList().get(0).getUserCardId()});
		if(qr.getTotalRecord()==0){
			throwExp("该rfid卡暂未绑定饭卡");
		}
		List<YrMealCardForm> formList = new ArrayList<YrMealCardForm>();
		if(qr.getTotalRecord()>0){
			formList.add(toForm(qr.getResultList().get(0)));
		}
		result.setData(formList);
		return result;
	}
	
	/**
	 * 饭卡充值
	 * @param cardPersonId
	 * @param userRfidCardId
	 * @param money
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("recharge")
	@ResponseBody
	public HTTPResult<YrMealCardRechargeRecordForm>  recharge(String cardPersonId ,Float pracMoney,Integer payType,String createId,Float preBalance) throws Exception{
		HTTPResult<YrMealCardRechargeRecordForm> result = new HTTPResult<YrMealCardRechargeRecordForm>();
		if(null==cardPersonId||null==pracMoney){
			throwExp("参数有误");
		}
//		if(pracMoney<=0){
//			throwExp("实际充值金额必须大于零");
//		}
		if(null!=preBalance&&preBalance<0){
			throwExp("赠送金额必须大于零");
		}
		String sqlWhere = "card_person_id=?1";
		QueryResult<YrMealCard> qrMealCard = selfService.find(YrMealCard.class, sqlWhere, new Object[]{cardPersonId});
		if(qrMealCard.getTotalRecord()==0){
			throwExp("查询不到该对象的饭卡");
		}
		YrMealCard mealCard = qrMealCard.getResultList().get(0);
		
		YrMealCardRechargeRecord preMealCardRechargeRecord = null;
		if(null!=preBalance&&preBalance>0){//如果有赠送充值
			preMealCardRechargeRecord = rechargePreBalance(mealCard,preBalance,createId);
		}
		
		mealCard.setBalance(mealCard.getBalance()+pracMoney);
		
		YrElderWallet elderWallet = null; 
		YrElderPayRecord elderPayRecord = null;
		
		String personName = "";
		String personCardId = "";
		if(mealCard.getPersonType()==1){//长者
			sqlWhere = "elder_id=?1";
			YrElder elder = elderService.findOne(cardPersonId);
			if(null==elder){
				throwExp("查询不到该老者相关信息");
			}
			personCardId = elder.getCardId();
			personName = elder.getName();
			if(payType==2){//如果是钱包充值
				QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere, new Object[]{cardPersonId});
				if(qrElderWallet.getTotalRecord()==0){
					throwExp("该老者暂无钱包");
				}
				elderWallet = qrElderWallet.getResultList().get(0);
				if(elderWallet.getWalletBalance()-pracMoney<0){
					throwExp("充值失败，钱包余额不足");
				}
				elderWallet.setWalletBalance(elderWallet.getWalletBalance()-pracMoney);
			}
			if(payType!=3){//如果支付方式不是包餐
			   sqlWhere = "elder_id=?1 AND be_status<>2";
				
				QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{cardPersonId});
				if(qrElderBeHospital.getResultList().isEmpty()){
					throwExp("查询不到相关老者住院登记信息");
				}
				elderPayRecord = costElderPayRecord(qrElderBeHospital.getResultList().get(0).getBeHospitalId(),"饭卡充值", elder, 10, mealCard.getMealCardId(), pracMoney, payType,0,createId,1);
			}
		}else {//职工
			if(payType==2){//如果是钱包充值 1钱包 2现金
				throwExp("职工只能使用现金充值");
			}
			YrStaffInfo staffInfo = staffInfoService.findOne(cardPersonId);
			if(null==staffInfo){
				throwExp("查询不到该职工相关信息");
			}
			personCardId = staffInfo.getCardId();
			personName = staffInfo.getName();
		}
		
		List<YrMealCardRechargeRecord> mealCardRechargeRecords = new ArrayList<YrMealCardRechargeRecord>();
		
		mealCardRechargeRecords.add(preMealCardRechargeRecord);
		//增加一条饭卡充值记录
		YrMealCardRechargeRecord mealCardRechargeRecord = 
				costMealCardRechargeRecord(mealCard, createId, pracMoney, pracMoney, payType, 2);
		
		mealCardRechargeRecords.add(mealCardRechargeRecord);
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrMealCard.class, mealCard);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(List.class, mealCardRechargeRecords);
		
		mealCard.setUpdateTime(new Date());
		
		selfService.executeRecharge(favorites);
		
		ArrayList<YrMealCardRechargeRecordForm> formList = new ArrayList<YrMealCardRechargeRecordForm>();
		YrMealCardRechargeRecordForm rechargeRecordForm = ObjectUtils.objectToObject(mealCardRechargeRecord, YrMealCardRechargeRecordForm.class);

		rechargeRecordForm.setMealCardBalance(mealCard.getBalance());
		rechargeRecordForm.setMealCardPreBalance(mealCard.getPreBalance());
		if(createId!=null){
			YrStaffInfo staffInfo = staffInfoService.findOne(createId);
			if(null!=staffInfo){
				rechargeRecordForm.setHandler(staffInfo.getName());
			}
		}
		formList.add(rechargeRecordForm);
		
		if(preMealCardRechargeRecord!=null){
			YrMealCardRechargeRecordForm preRechargeRecordForm = ObjectUtils.objectToObject(preMealCardRechargeRecord, YrMealCardRechargeRecordForm.class);
			preRechargeRecordForm.setHandler(rechargeRecordForm.getHandler());
			preRechargeRecordForm.setMealCardBalance(mealCard.getBalance());
			preRechargeRecordForm.setMealCardPreBalance(mealCard.getPreBalance());
			formList.add(preRechargeRecordForm);
		}

		result.setData(formList);
		
		return result;
	}
	
	/**
	 * 
	 * @param mealCard 饭卡
	 * @param createId 创建者id
	 * @param rechargeMoney 充值金额
	 * @param pracMoney 实充金额
	 * @param payType 充值(1现金2钱包3包餐4赠送充值5赠送余额清零)
	 * @param rechargeType 充值类型(1赠送2自主充值)
	 * @return
	 */
	public YrMealCardRechargeRecord costMealCardRechargeRecord(YrMealCard mealCard,String createId,Float rechargeMoney,Float pracMoney,Integer payType,Integer rechargeType){
		YrMealCardRechargeRecord mealCardRechargeRecord = new YrMealCardRechargeRecord();
		mealCardRechargeRecord.setMealCardRechargeRecordId(UUIDGenerator.getUUID());
		mealCardRechargeRecord.setCardPersonId(mealCard.getCardPersonId());
		mealCardRechargeRecord.setCardCardId(mealCard.getCardCardId());
		mealCardRechargeRecord.setCardPersonName(mealCard.getCardPersonName());
		mealCardRechargeRecord.setCardType(mealCard.getCardType());
		mealCardRechargeRecord.setCreateTime(new Date());
		mealCardRechargeRecord.setCreateId(createId);
		mealCardRechargeRecord.setPersonType(mealCard.getPersonType());
		mealCardRechargeRecord.setRechargeMoney(rechargeMoney);
		mealCardRechargeRecord.setRechargeDate(new Date());
		mealCardRechargeRecord.setRechargeSource(payType);
		mealCardRechargeRecord.setPracRechargeMoney(pracMoney);
		mealCardRechargeRecord.setRechargeType(rechargeType);
		
		return mealCardRechargeRecord;
	}
	
	
	@RequestMapping("slotMeal")
	@ResponseBody
	public HTTPResult<YrMealCardForm> slotMeal(String mealCardId,String mealsId) throws MyException{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		if(null==mealCardId||null==mealsId){
			throwExp("参数有误");
		}
		YrMealCard mealCard = selfService.findOne(mealCardId);
		if(null==mealCard){
			throwExp("饭卡不存在");
		}
		YrMeal meal = mealService.findOne(mealsId);
		if(null== meal){
			throwExp("餐费不存在");
		}
		
		ArrayList<YrMealsCostRecord> mealsCostRecords = new ArrayList<YrMealsCostRecord>();
		Integer payResource = 1;//消费来源 1赠送余额2余额
		
		if(mealCard.getPreBalance()!=null&&mealCard.getPreBalance()-meal.getPrice()>=0){//优先消费赠送余额
			mealCard.setPreBalance(mealCard.getPreBalance()-meal.getPrice());
			//增加一条饭卡消费记录
			YrMealsCostRecord mealsCostRecord = constMealsCostRecord(mealCard, meal,meal.getPrice(),1);
			mealsCostRecords.add(mealsCostRecord);
		}else{
			Float prePay  = 0F ;
			YrMealsCostRecord mealsCostRecord = null;
			if(mealCard.getPreBalance()!=null&&mealCard.getPreBalance()>0){//如果赠送余额有剩余，先消费赠送余额
				prePay = mealCard.getPreBalance();//赠送余额支付
				mealCard.setPreBalance(0F);
				//增加一条饭卡消费记录
				mealsCostRecord = constMealsCostRecord(mealCard, meal,prePay,1);
				mealsCostRecords.add(mealsCostRecord);
			}
			Float pay = meal.getPrice()-prePay;
			if(mealCard.getBalance()-pay<0){//减去赠送的部分
				throwExp("饭卡余额不足");
			}
			mealCard.setBalance(mealCard.getBalance()-pay);
			//增加一条饭卡消费记录
			mealsCostRecord = constMealsCostRecord(mealCard, meal,pay,2);
			mealsCostRecords.add(mealsCostRecord);
		}

		Favorites favorites = new Favorites();
		favorites.putFavorite(YrMealCard.class, mealCard);
		favorites.putFavorite(ArrayList.class, mealsCostRecords);
		
		selfService.executeSlotMeal(favorites);
		
		return result;
	}
	
	
	private YrMealsCostRecord constMealsCostRecord(YrMealCard mealCard,YrMeal meal,Float price,Integer payResource){
		//增加一条饭卡消费记录
		YrMealsCostRecord mealsCostRecord = new YrMealsCostRecord();
		mealsCostRecord.setMealsCostRecordId(UUIDGenerator.getUUID());
		mealsCostRecord.setUserRfidCardId(mealCard.getUserRfidCardId());
		mealsCostRecord.setUserRelationId(mealCard.getCardPersonId());
		mealsCostRecord.setUserType(mealCard.getPersonType());
		mealsCostRecord.setMealsName(meal==null?"自定义餐费":meal.getMealsName());
		mealsCostRecord.setMealPrice(meal==null?price:meal.getPrice());
		mealsCostRecord.setMealsId(meal==null?"-1":meal.getMealsId());
		mealsCostRecord.setPayMoney(price);
		mealsCostRecord.setMealsType(meal==null?"自定义":meal.getType());
		mealsCostRecord.setUserName(mealCard.getCardPersonName());
		mealsCostRecord.setUserCardId(mealCard.getCardCardId());
		mealsCostRecord.setMealCardId(mealCard.getMealCardId());
		mealsCostRecord.setPayDate(new Date());
		mealsCostRecord.setCreateTime(new Date());
		mealsCostRecord.setCreateId("-1");
		mealsCostRecord.setPayResource(payResource);
		return mealsCostRecord;
	}
	
	@RequestMapping("slotMealByCustom")
	@ResponseBody
	public HTTPResult<YrMealCardForm> slotMealByCustom(String mealCardId,float price) throws MyException{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		if(null==mealCardId){
			throwExp("参数有误");
		}
		YrMealCard mealCard = selfService.findOne(mealCardId);
		if(null==mealCard){
			throwExp("饭卡不存在");
		}
		if(mealCard.getBalance()-price<0){
			throwExp("饭卡余额不足");
		}
		ArrayList<YrMealsCostRecord> mealsCostRecords = new ArrayList<YrMealsCostRecord>();
		if(mealCard.getPreBalance()!=null&&mealCard.getPreBalance()-price>=0){//优先消费赠送余额
			mealCard.setPreBalance(mealCard.getPreBalance()-price);
			//增加一条饭卡消费记录
			YrMealsCostRecord mealsCostRecord = constMealsCostRecord(mealCard, null,price,1);
			mealsCostRecords.add(mealsCostRecord);
		}else{
			Float prePay  = 0F ;
			YrMealsCostRecord mealsCostRecord = null;
			if(mealCard.getPreBalance()!=null&&mealCard.getPreBalance()>0){//如果赠送余额有剩余，先消费赠送余额
				prePay = mealCard.getPreBalance();//赠送余额支付
				mealCard.setPreBalance(0F);
				//增加一条饭卡消费记录
				mealsCostRecord = constMealsCostRecord(mealCard, null,prePay,1);
				mealsCostRecords.add(mealsCostRecord);
			}
			Float pay = price-prePay;
			if(mealCard.getBalance()-pay<0){//减去赠送的部分
				throwExp("饭卡余额不足");
			}
			mealCard.setBalance(mealCard.getBalance()-pay);
			//增加一条饭卡消费记录
			mealsCostRecord = constMealsCostRecord(mealCard, null,pay,2);
			mealsCostRecords.add(mealsCostRecord);
		}
		
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrMealCard.class, mealCard);
		favorites.putFavorite(ArrayList.class, mealsCostRecords);
		
		selfService.executeSlotMeal(favorites);
		
		return result;
	}	
	
	/**
	 * 查询首次赠送列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("findElderFirstPreList")
	@ResponseBody
	public HTTPResult<YrMealCardForm> findElderFirstPreList() throws Exception{
		HTTPResult<YrMealCardForm> result = new HTTPResult<>();
		String sql = "SELECT a FROM YrMealCard a, YrElderBeHospital b "
				+ "WHERE a.cardPersonId = b.elderId AND a.personType=1 AND a.prePreTime is null AND b.beStatus=0";
		List<YrMealCard> mealCardList = selfService.findByJPQL(sql,new Object[]{});
		System.out.println("size = "+mealCardList.size());
		List<YrMealCardForm> formList = new ArrayList<YrMealCardForm>();
		for(YrMealCard entity : mealCardList){
			YrMealCardForm form = toForm(entity);
			
			//设置距离上次充值天数
			form.setPreDisDays(-1);
			
			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere,new Object[]{entity.getCardPersonId()});
			if(qrElderBeHospital.getTotalRecord()>0){
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(qrElderBeHospital.getResultList().get(0), YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	/**
	 * 查询正在住院处理列表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findElderPreList")
	@ResponseBody
	public HTTPResult<YrMealCardForm> findElderPreList() throws Exception{
		HTTPResult<YrMealCardForm> result = new HTTPResult<>();
		String sql = "SELECT a FROM YrMealCard a, YrElderBeHospital b "
				+ "WHERE a.cardPersonId = b.elderId AND a.personType=1 AND a.prePreTime is not null AND b.beStatus<>2 "
				+ "AND (datediff(CURDATE(),a.prePreTime)>=30)";
		List<YrMealCard> mealCardList = selfService.findByJPQL(sql,new Object[]{});
		System.out.println("size = "+mealCardList.size());
		List<YrMealCardForm> formList = new ArrayList<YrMealCardForm>();
		for(YrMealCard entity : mealCardList){
			YrMealCardForm form = toForm(entity);
			
			//设置距离上次充值天数
			Integer	days = DateUtil.daysOfTwo(entity.getPrePreTime(),new Date());
			form.setPreDisDays(days);
			
			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere,new Object[]{entity.getCardPersonId()});
			if(qrElderBeHospital.getTotalRecord()>0){
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(qrElderBeHospital.getResultList().get(0), YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	/**
	 * 清零
	 * @param id
	 * @param commParamForm
	 * @return
	 * @throws MyException
	 * @throws SwallowException
	 */
	@RequestMapping("resetPreBalance")
	@ResponseBody
	public HTTPResult<YrMealCardForm> resetPreBalance(String id,String commParamForm) throws MyException, SwallowException{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		if(StringUtils.isEmpty(id)){
			throwExp("参数有误");
		}
		
		YrMealCard mealCard = selfService.findOne(id);
		if(mealCard==null){
			throwExp("查询不到饭卡");
		}
		if(mealCard.getPreBalance()==null||mealCard.getPreBalance()<=0){
			throwExp("赠送余额为零或已经清零，无需清零");
		}
		
		JsonMapperTool tool = new JsonMapperTool(commParamForm);
		CommParamForm loginedUser = tool.mapper("loginedUser",CommParamForm.class);
		
		mealCard.setPreBalance(0F);
		mealCard.setUpdateTime(new Date());
		mealCard.setUpdateId(loginedUser.getStaffId());
		
		//增加一条饭卡充值记录（清零记录）
		YrMealCardRechargeRecord mealCardRechargeRecord = 
				costMealCardRechargeRecord(mealCard, loginedUser.getStaffId(), -mealCard.getPreBalance(), 0F, 5, 1);
	
		selfService.save(mealCard);
		mealCardRechargeRecordService.save(mealCardRechargeRecord);
		
		return result;
	}
	
	/**
	 * 批量清零赠送余额
	 * @param data
	 * @param commParamForm
	 * @return
	 * @throws SwallowException
	 * @throws MyException
	 */
	@RequestMapping("resetPreBalanceBatch")
	@ResponseBody
	public HTTPResult<YrMealCardForm> resetPreBalanceBatch(String data,String commParamForm) throws SwallowException, MyException{
		HTTPResult<YrMealCardForm> result = new HTTPResult<YrMealCardForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		String[] ids = tool.mapper("ids", String[].class);
		CommParamForm loginedUser = tool.mapper("commParamForm",CommParamForm.class);
		
		if(null==ids){
			throwExp("param.error");
		}
		for(String id : ids){
			YrMealCard mealCard = selfService.findOne(id);
			if(mealCard.getPreBalance()>0){//赠送余额大于0 则清零
				mealCard.setPreBalance(0F);
				mealCard.setUpdateTime(new Date());
				mealCard.setUpdateId(loginedUser.getStaffId());
				
				//增加一条饭卡充值记录（清零记录）
				YrMealCardRechargeRecord mealCardRechargeRecord = 
						costMealCardRechargeRecord(mealCard, loginedUser.getStaffId(), -mealCard.getPreBalance(), 0F, 5, 1);
			
				selfService.save(mealCard);
				mealCardRechargeRecordService.save(mealCardRechargeRecord);
			}
		}
		return result;
	}
	
	/**
	 * 充值赠送余额
	 * @param id
	 * @return
	 * @throws MyException
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws SwallowException 
	 */
	@RequestMapping("rechargePreBalance")
	@ResponseBody
	public HTTPResult<YrMealCardRechargeRecordForm> rechargePreBalance(String id,Float money,String commParamForm) throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SwallowException{
		HTTPResult<YrMealCardRechargeRecordForm> result = new HTTPResult<YrMealCardRechargeRecordForm>();
		
		if(StringUtils.isEmpty(id)||money==null){
			throwExp("参数有误");
		}
		
		YrMealCard mealCard = selfService.findOne(id);
		if(mealCard==null){
			throwExp("查询不到饭卡");
		}
		
		JsonMapperTool tool = new JsonMapperTool(commParamForm);
		CommParamForm loginedUser = tool.mapper("loginedUser",CommParamForm.class);
		
		YrMealCardRechargeRecord mealCardRechargeRecord = rechargePreBalance(mealCard,money, loginedUser.getStaffId());

		selfService.save(mealCard);
		mealCardRechargeRecordService.save(mealCardRechargeRecord);
		
		ArrayList<YrMealCardRechargeRecordForm> formList = new ArrayList<YrMealCardRechargeRecordForm>();
		YrMealCardRechargeRecordForm rechargeRecordForm = ObjectUtils.objectToObject(mealCardRechargeRecord, YrMealCardRechargeRecordForm.class);
		
		rechargeRecordForm.setMealCardBalance(mealCard.getBalance());
		rechargeRecordForm.setMealCardPreBalance(mealCard.getPreBalance());
		if(loginedUser.getStaffId()!=null){
			YrStaffInfo staffInfo = staffInfoService.findOne(loginedUser.getStaffId());
			if(null!=staffInfo){
				rechargeRecordForm.setHandler(staffInfo.getName());
			}
		}

		formList.add(rechargeRecordForm);
		
		result.setData(formList);
		
		return result;
	}
	
	private YrMealCardRechargeRecord rechargePreBalance(YrMealCard mealCard,Float money,String createId) throws MyException{

		Date preDate = mealCard.getPrePreTime();
		Date now = new Date();	
		if(preDate!=null){
			if(DateUtil.isInCurrMonth(preDate)){
				throwExp("当前饭卡本月已经赠送过，不能再次赠送");
			}
			if(mealCard.getPersonType()==2&&money>100){
				throwExp("职工的饭卡赠送金额不能大于100/次");
			}
//			Integer days = DateUtil.daysOfTwo(preDate, now);
//			if(days<30){
//				throwExp("距离上次赠送余额未满30天，不能赠送");
//			}
		}
		mealCard.setPreBalance(money);
		mealCard.setPrePreTime(now);
		
		//增加一条饭卡充值记录
		YrMealCardRechargeRecord mealCardRechargeRecord = 
				costMealCardRechargeRecord(mealCard, createId, money, 0F, 4, 1);
		
		return mealCardRechargeRecord;
	}
	
	/**
	 * 获取员工饭卡列表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findStaffPreList")
	@ResponseBody
	public HTTPResult<YrMealCardForm> findStaffPreList() throws Exception{
		HTTPResult<YrMealCardForm> result = new HTTPResult<>();
		String sql = "SELECT a FROM YrMealCard a, YrStaffInfo b "
				+ "WHERE a.cardPersonId = b.staffId AND a.personType=2 "
				+ "AND (a.prePreTime is null OR datediff(CURDATE(),a.prePreTime)>=30)";
		List<YrMealCard> mealCardList = selfService.findByJPQL(sql,new Object[]{});
		System.out.println("size = "+mealCardList.size());
		List<YrMealCardForm> formList = new ArrayList<YrMealCardForm>();
		for(YrMealCard entity : mealCardList){
			YrMealCardForm form = toForm(entity);
			//设置距离上次充值天数
			Integer days = -1;
			if(entity.getPrePreTime()!=null){
				days = DateUtil.daysOfTwo(entity.getPrePreTime(),new Date());
			}
			form.setPreDisDays(days);
			
			YrStaffInfo staffInfo = staffInfoService.findOne(entity.getCardPersonId());
			if(staffInfo!=null){
				form.setStaffInfoForm(ObjectUtils.objectToObject(staffInfo, YrStaffInfoForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@Override
	public YrMealCardForm toForm(YrMealCard e) throws Exception {
		YrMealCardForm form = ObjectUtils.objectToObject(e, YrMealCardForm.class);
		return form;
	}

	@Override
	public YrMealCard toEntity(YrMealCardForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
